package controllers;

import java.util.Map;

import javax.mail.MessagingException;

import model.forview.IndexModelForView;
import model.forview.LoginModelForView;
import model.forview.RecoveryModelForView;
import model.forview.RegistrationModelForView;
import model.wrap.user.User;
import model.wrap.user.UserException;
import play.data.Form;
import play.mvc.*;
import security.Security;

import utils.Emailer;
import views.html.*;

/**
 * 
 * @author pocteg
 * 
 */
public class Application extends Controller
{

    public static Result index()
    {
	IndexModelForView model = new IndexModelForView();
	return ok(index.render(model));
    }

    public static Result getPageLogin()
    {
	LoginModelForView model = new LoginModelForView();
	return ok(login.render(model));
    }

    public static Result login()
    {
	LoginModelForView requestForm = new LoginModelForView(form().bindFromRequest().data());
	try
	{
	    Security.authorization(requestForm);
	    return redirect(routes.Hierarchy.structures(""));
	}
	catch (Exception e)
	{
	    return redirect(routes.Application.getPageLogin());
	}
    }

    public static Result logoff()
    {
	try
	{
	    Security.logoff();
	    return redirect(routes.Application.index());
	}
	catch (Exception e)
	{
	    return redirect(routes.Application.index());
	}
    }

    public static Result getPageRecovery()
    {
	RecoveryModelForView model = new RecoveryModelForView();
	return ok(views.html.getPageRecovery.render(model));
    }

    public static Result recovery()
    {
	RecoveryModelForView model = new RecoveryModelForView(form().bindFromRequest().data());
	try
	{
	    User user = new User(model.getEmail());
	    user.setRandomPassword();
	    user.update();
	    
	    //TODO использовать flash + редирект
	    Emailer.sendEmail(model.getEmail(), "Восстановление пароля", "Ваш новый пароль - "+user.getPassword());
	    model.setStatusMessage("Письмо отправленно на " + model.getEmail() + ".");
	    return ok(views.html.getPageRecovery.render(model));
	}
	catch (MessagingException e)
	{
	    model.setStatusMessage("Произошла ошибка. Обратитесь к администратору.");
	    return ok(views.html.getPageRecovery.render(model));
	}
	catch (UserException e)
	{
	    model.setStatusMessage("Произошла ошибка. " + e.getMessage());
	    return ok(views.html.getPageRecovery.render(model));
	}
    }

    public static Result getPageRegistration()
    {
	RegistrationModelForView forModel = new RegistrationModelForView();
	return ok(registration.render(forModel));
    }

    public static Result registration()
    {
	RegistrationModelForView data = new RegistrationModelForView(form().bindFromRequest().data());
	User user = new User(data);
	user.save();
	return redirect(routes.Application.index());// (registration.render(requestForm.get()));
    }

}